package com.keenote.http;

import com.keenote.http.CookieManager;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * description
 *
 * @author mic.zhou
 * @date 2022/8/23 10:58
 */
public class HttpUtils {
    private static final RestTemplate restTemplate;

    static {
        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory();
        factory.setConnectTimeout(10000);
        factory.setReadTimeout(120000);
        factory.setWriteTimeout(120000);
        restTemplate = new RestTemplate(factory);
    }

    /**
     * GET 对象
     *
     * @param url          url
     * @param responseType 返回类型
     * @param <T>          结果类型
     * @return 结果
     */
    public static <T> T get(String url, Class<T> responseType) {
        HttpEntity<?> entity = new HttpEntity<>(CookieManager.getCookieHeader(url));
        return restTemplate.exchange(url, HttpMethod.GET, entity, responseType).getBody();
    }

    /**
     * GET 对象
     *
     * @param url          url
     * @param responseType 返回类型
     * @param httpHeaders  httpHeaders
     * @param <T>          结果类型
     * @return 结果
     */
    public static <T> T get(String url, HttpHeaders httpHeaders, Class<T> responseType) {
        HttpHeaders headers = CookieManager.getCookieHeader(url);
        headers.addAll(httpHeaders);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(url, HttpMethod.GET, entity, responseType).getBody();
    }


    /**
     * post 对象
     *
     * @param url          url
     * @param body         body
     * @param responseType 返回类型
     * @param <T>          结果类型
     * @return 结果
     */
    public static <T> T post(String url, Object body, Class<T> responseType) {
        HttpEntity<?> entity = new HttpEntity<>(body, CookieManager.getCookieHeader(url));
        return restTemplate.exchange(url, HttpMethod.POST, entity, responseType).getBody();
    }

    /**
     * post 对象
     *
     * @param url          url
     * @param body         body
     * @param responseType 返回类型
     * @param headers      headers
     * @param <T>          结果类型
     * @return 结果
     */
    public static <T> T post(String url, Object body, HttpHeaders headers, Class<T> responseType) {
        HttpHeaders httpHeaders = CookieManager.getCookieHeader(url);
        httpHeaders.addAll(headers);
        HttpEntity<?> entity = new HttpEntity<>(body, httpHeaders);
        return restTemplate.exchange(url, HttpMethod.POST, entity, responseType).getBody();
    }

}
